/**
 * @description user API 路由
 * @author 高
 */

const router = require("koa-router")();
const { isExist, register, login, deleteCurUser, changeInfo, changePassword, logout } = require("../../controller/user");
const userValidate = require("../../validator/user");
const { genValidator } = require("../../middlewares/validator");
const { isTest } = require("../../utils/env");
const { loginCheck } = require("../../middlewares/loginChecks");
const { changeInfoFailInfo } = require("../../model/ErrorInfo");

// 路由前缀
router.prefix("/api/user");


// 注册路由
// 可以定义两个中间件
router.post("/register", genValidator(userValidate), async (ctx, next) => {
  const { userName, password, gender } = ctx.request.body;
  // 留坑->controller
  ctx.body = await register({ userName, password, gender });
});


// 用户名是否存在
router.post("/isExist", async (ctx, next) => {
  const { userName } = ctx.request.body;
  ctx.body = await isExist(userName);
});

// 登录
router.post("/login", async (ctx, next) => {
  const { userName, password } = ctx.request.body;
  // controller
  ctx.body = await login(ctx, userName, password);
});

// 删除
router.post("/delete", loginCheck, async (ctx, nest) => {
  if (isTest) {
    // 为了保证测试安全，只能删除自己，不能删除其他人
    // 测试环境下，测试账号登录之后，删除自己
    const { userName } = ctx.session.userInfo;
    // 调用controller
    ctx.body = await deleteCurUser(userName);
  }
});

// 修改个人信息,检查用户是否登录，验证上传信息数据格式
router.patch("/changeInfo", loginCheck, genValidator(userValidate), async (ctx, next) => {

  // 获取参数
  const { nickName, city, picture } = ctx.request.body;
  // controller
  ctx.body = await changeInfo(ctx, { nickName, city, picture });
});

// 修改密码,检查用户是否登录，验证信息数据格式
router.patch("/changePassword", loginCheck, genValidator(userValidate), async (ctx, next) => {
  const { password, newPassword } = ctx.request.body;
  const { userName } = ctx.session.userInfo;
  // controller
  ctx.body = await changePassword(userName, password, newPassword);
});

// 退出登录
router.post("/logout", loginCheck, async (ctx, next) => {
  // controller
  ctx.body = await logout(ctx);
});

module.exports = router;